<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
//引用对应的命名空间
use Gregwar\Captcha\CaptchaBuilder;
use Session;


class LoginController extends Controller
{
    //前台登录页面
    public function login(){
        return view('/home/login');
    }

    //登录验证操作
    public function checklogin(Request $request){
        //验证 验证码是否正确
        $userInput = \Request::get('captcha');

        if (Session::get('milkcaptcha') != $userInput) {
            //用户输入验证码错误
            return error('/home/login','输入验证码错误',3);
        }

        //接收表信息
        $uname = $request->input('uname');
        $upwd = md5($request->input('upwd'));
        //var_dump($uname);
        //var_dump($upwd);

        //查询用户信息
        $result = DB::table('users')
                        ->where('uname','=',$uname)
                        ->where('upwd','=',$upwd)
                        ->select('uid','uname','uemail')
                        ->first();

        //var_dump($result);
        if($result){
            //查询到用户  写入session信息并跳转到前台首页
            $request->session()->put('isHome',true);//登录标志
            $request->session()->put('uid',$result['uid']);//用户ID
            $request->session()->put('uname',$result['uname']);//用户名
            $request->session()->put('uemail',$result['uemail']);//用户邮箱

            //跳转到首页
            return redirect('/home/index');

        }else{
            return redirect('/home/login');
        }
    }

    //退出清除session信息
    public function logout(Request $request){
        //清除session信息
        $request->session()->flush();
        //跳转页面
        return redirect('/home/index');
    }

    //生成验证码的方法
    public function vcode(){
        //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        Session::flash('milkcaptcha', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();

    }
}
